package cn.zt.controller;


import cn.zt.domain.dao.Airline;
import cn.zt.domain.dto.FlightDTO;
import cn.zt.domain.pojo.Result;
import cn.zt.service.IManageService;
import cn.zt.service.ISelectService;
import cn.zt.utils.ExcelUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/manage")
public class ManageController {

    @Resource
    private ISelectService selectService;
    @Resource
    private IManageService manageService;

    /**
     * 导出航班信息列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestBody FlightDTO flightDTO)
    {
        System.out.println("导出航班信息列表");
        System.out.println(flightDTO.geteDestination() + " " + flightDTO.getbDestination() +
                " " + flightDTO.getbDate() + " " + flightDTO.geteDate());
        List<Airline> list = selectService.selectAirlineList(flightDTO);
        if (list == null || list.isEmpty()) {
            System.out.println("查询结果为空");
            // 可以选择抛出异常或返回提示信息给前端
            throw new RuntimeException("没有找到符合条件的航班信息");
        } else {
            System.out.println("查询到的航班信息数量: " + list.size());
        }
        ExcelUtil<Airline> util = new ExcelUtil<>(Airline.class);
        util.exportExcel(response, list, "航班信息数据");
    }

    /**
     * 导入航班信息列表
     */
    @PostMapping("/import")
    @ResponseBody
    public Result importData(MultipartFile file) throws Exception
    {
        System.out.println("file:"+file);
        if (file == null || file.isEmpty()) {
            return Result.fail("文件不能为空");
        }
        try {
            ExcelUtil<Airline> util = new ExcelUtil<>(Airline.class);
            List<Airline> list = util.importExcel(file.getInputStream());
            String message = manageService.importFlightinfo(list, true);
            System.out.println(message);
            return Result.ok(message);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("导入失败: " + e.getMessage());
        }
    }

}
